/**
 * 金额处理工具集
 */

/**
 * 格式化金额：加千分位逗号，保留指定小数位
 * @param amount - 原始金额（数字或字符串）
 * @param decimals - 保留的小数位数，默认 2
 * @returns 格式化后的字符串
 * @example
 * formatAmount(1234567.89) // "1,234,567.89"
 */
export function formatAmount(amount: number | string, decimals = 2): string {
  const num = Number(amount)
  if (Number.isNaN(num))
    return '0.00'
  return num.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

/**
 * 四舍五入金额到指定小数位
 * @param amount - 原始金额
 * @param decimals - 保留小数位数
 * @returns 四舍五入后的数字
 * @example
 * roundAmount(123.4567, 2) // 123.46
 */
export function roundAmount(amount: number | string, decimals = 2): number {
  const num = Number(amount)
  if (Number.isNaN(num))
    return 0
  const factor = 10 ** decimals
  return Math.round(num * factor) / factor
}

/**
 * 去除金额格式（如逗号），转为纯数字字符串
 * @param formattedAmount - 已格式化的金额字符串
 * @returns 去格式后的金额字符串
 * @example
 * unformatAmount("1,234,567.89") // "1234567.89"
 */
export function unformatAmount(formattedAmount: string): string {
  return formattedAmount.replace(/,/g, '')
}

/**
 * 将金额转换为中文大写形式
 * @param amount - 金额（数字或字符串）
 * @returns 中文大写金额字符串
 * @example
 * amountToChinese(1234.56) // "壹仟贰佰叁拾肆元伍角陆分"
 */
export function amountToChinese(amount: number | string): string {
  const num = Number(amount)
  if (Number.isNaN(num))
    return '零元整'

  const units = ['元', '万', '亿']
  const chars = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const radices = ['', '拾', '佰', '仟']
  const decimals = ['角', '分']

  const [integerPart, decimalPart = ''] = num.toFixed(2).split('.')

  let result = ''
  let integer = Number(integerPart)

  if (integer === 0) {
    result = '零元'
  }
  else {
    let unitPos = 0

    while (integer > 0) {
      let section = integer % 10000
      let sectionStr = ''
      let zero = true

      for (let i = 0; i < 4 && section > 0; i++) {
        const digit = section % 10
        if (digit === 0) {
          if (!zero) {
            sectionStr = chars[0] + sectionStr
            zero = true
          }
        }
        else {
          sectionStr = chars[digit] + radices[i] + sectionStr
          zero = false
        }
        section = Math.floor(section / 10)
      }

      if (sectionStr !== '') {
        result = sectionStr + units[unitPos] + result
      }

      unitPos++
      integer = Math.floor(integer / 10000)
    }
  }

  if (Number(decimalPart) === 0) {
    result += '整'
  }
  else {
    for (let i = 0; i < decimals.length; i++) {
      const digit = Number(decimalPart[i])
      if (digit > 0) {
        result += chars[digit] + decimals[i]
      }
    }
  }

  return result.replace(/零+/g, '零').replace(/零元/, '元').replace(/^元/, '零元')
}
